﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Goldlight.Mvvm.Base.Behaviors
{
    /// <summary>
    /// Ensure that a textbox handles numeric data only.
    /// </summary>
    public class NumericTextboxBehavior
    {
        /// <summary>
        /// Dependency property to ensure that a textbox can be numeric only.
        /// </summary>
        public static DependencyProperty NumericProperty = 
            DependencyProperty.RegisterAttached("Numeric", typeof(TextBox), typeof(NumericTextboxBehavior),
            new FrameworkPropertyMetadata(null, new PropertyChangedCallback(NumericChanged)));

        private static void NumericChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            TextBox element = target as TextBox;

            if (element != null)
            {
                if (e.NewValue != null && e.OldValue == null)
                {
                    element.PreviewTextInput += new TextCompositionEventHandler(element_PreviewTextInput);
                    DataObject.AddPastingHandler(target, PastingHandler);
                }
                else if (e.NewValue == null && e.OldValue != null)
                {
                    element.PreviewTextInput -= new TextCompositionEventHandler(element_PreviewTextInput);
                    DataObject.RemovePastingHandler(target, PastingHandler);
                }
            }
        }

        /// <summary>
        /// Event handler to prevent the clipboard posting non-numeric data into the textbox.
        /// </summary>
        static void PastingHandler(object sender, DataObjectPastingEventArgs dopea)
        {
            string clipboard = dopea.DataObject.GetData(typeof(string)) as string;
            double value;
            if (!double.TryParse(clipboard, out value))
            {
                dopea.CancelCommand();
                dopea.Handled = true;
            }
        }

        /// <summary>
        /// Ensure that the textbox does not accept non-numeric data.
        /// </summary>
        static void element_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            double value;
            if (!double.TryParse(e.Text, out value))
            {
                e.Handled = true;
            }
        }
    }
}
